<template>
  <!-- 最外层的容器 -->
  <view class="my-settle-container">
     <!-- 全选区域 -->
      <label class="radio" @click="changeAllGoodsState">
        <radio color="#C00000" :checked="isAllCheck" /><text>全选</text>
      </label>

      <!-- 合计区域 -->
      <view class="amount-box">
        合计:<text class="amount">￥{{totalPrice}}</text>
      </view>
      
      <!-- 结算区域 -->
      <view class="btn-settle" @click="settlement">结算({{checkedAmount}})</view>
  </view>
</template>

<script>
  
  import { mapGetters, mapState, mapMutations } from 'vuex'
  
  
  export default {
    name:"my-settle",
    data() {
      return {
        // 倒计时时间
        seconds: 3
      };
    },
    computed: {
      ...mapGetters('m_cart', ['isAllCheck', 'totalPrice', 'checkedAmount']),
      ...mapGetters('m_user', ['addstr']),
      ...mapState('m_user', ['token']),
      ...mapState('m_cart', ['cart']),
    },
    methods: {
      ...mapMutations('m_cart', ['updateAllGoodsState']),
      ...mapMutations('m_user', ['saveRedirectInfo']),
      changeAllGoodsState(){
        console.log('====')
        this.updateAllGoodsState(!this.isAllCheck)
      },
      // 结算条件判断
      settlement(){
        // 1 收获地址 
        if(!this.addstr) return uni.$showMsg('请选择收获地址')
        // 2 至少勾选一件商品 
        if(this.checkedAmount < 1) return uni.$showMsg('请至少选择一件商品')
        // 3 用户要登录（token）
        // if(!this.token) return uni.$showMsg('请登录')
        if(!this.token) return this.dealyNavigate()
        
        console.log('准备zhifu')
        this.payOrder()
      },
      // 倒计时提示
      dealyNavigate(){
        for(let i = 0; i<=this.seconds; i++) {
            setTimeout(() => {
                console.log('倒计时', this.seconds-i)
                if(i === 3){
                  // 跳转到个人
                  console.log('tiao', '保存from从哪里的信息', 'cart')
                  uni.switchTab({
                    url: '/pages/my/my',
                    success: () => {
                      // 保存跳转信息
                      this.saveRedirectInfo({
                        // 跳转的方式
                        openType: 'switchTab',
                        // 从哪个页面跳转过去的
                        from: '/pages/cart/cart'
                      })
                    }
                  })
                }else{
                  uni.showToast({
                    title: `未登录，将在${this.seconds-i}秒后跳转到登录页面`,
                    duration: 1000,
                    mask: true,
                    icon: 'none'
                  })
                }
            }, i*1000)
        
        }
      },
      async payOrder() {
        // 1 创建订单 
        const data = {
          // order_price: this.totalPrice,
          order_price: 0.01,
          consignee_addr: this.addstr,
          goods: this.cart.filter(item => item.goods_state)
                          .map(item => ({
                            goods_id: item.goods_id,
                            goods_number: item.goods_count,
                            goods_price: item.goods_price
                          }))
        }
        
        const { data: res } = await uni.$http.post('/my/orders/create', data)
        // 异常数据判断
        if (res.meta.status !== 200) return uni.$showMsg('创建订单失败！')
        // 1.3 得到服务器响应的“订单编号”
        const orderNumber = res.message.order_number
        console.log('orderNumber', orderNumber)
        
        // 2 请求支付参数 
        const { data: res2 } = await uni.$http.post('/my/orders/req_unifiedorder', { order_number: orderNumber })
        // 2.2 预付订单生成失败
        if (res2.meta.status !== 200) return uni.$showMsg('预付订单生成失败！')
        // 2.3 得到订单支付相关的必要参数
        const payInfo = res2.message.pay
        console.log('订单支付参数', payInfo)
        
        // 3 发起微信支付 
        const [err, succ] = await uni.requestPayment(payInfo)
        // 3.2 未完成支付
        if (err) return uni.$showMsg('订单未支付！')
        console.log('微信支付成功', succ)
        
        // 4 确认钱到账（公司）
         const { data: res3 } = await uni.$http.post('/my/orders/chkOrder', { order_number: orderNumber })
         // 4.1 检测到订单未支付
         if (res3.meta.status !== 200) return uni.$showMsg('订单未支付！')
         // 4.2 检测到订单支付完成
         uni.showToast({
           title: '支付完成！',
           icon: 'success'
         })
      }
    },

  }
</script>

<style lang="scss">
.my-settle-container {
  /* 底部固定定位 */
  position: fixed;
  bottom: 0;
  left: 0;
  /* 设置宽高和背景色 */
  width: 100%;
  height: 50px;
  background-color: white; // 将背景色从 cyan 改为 white
  z-index: 9;
  
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-left: 5px;
  font-size: 14px;

  .radio {
    display: flex;
    align-items: center;
  }

  .amount-box {
    .amount {
      color: #c00000;
    }
  }

  .btn-settle {
    height: 50px;
    min-width: 100px;
    background-color: #c00000;
    color: white;
    line-height: 50px;
    text-align: center;
    padding: 0 10px;
  }
}
</style>
